package kr.pe.johnkim.carrotpoint.mobile.controller;

import kr.pe.johnkim.carrotpoint.mobile.domain.CarrotPointMember;
import kr.pe.johnkim.carrotpoint.mobile.domain.ImageFile;
import kr.pe.johnkim.carrotpoint.mobile.service.CarrotPointMemberService;
import kr.pe.johnkim.carrotpoint.mobile.util.CarrotPointCommon;
import kr.pe.johnkim.carrotpoint.mobile.util.CarrotPointConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * Carrot Point 사용자 관련 controller 클래스 이다.
 *
 * @author : johnkim <cale9797@gmail.com>
 * @date: 13. 1. 31.
 */
@Controller
@RequestMapping(value = "/carrotPointMemberController")
public class CarrotPointMemberController {

    // SLF4J Logging
    private Logger logger = LoggerFactory.getLogger(CarrotPointMemberController.class);

    @Autowired
    CarrotPointMemberService carrotPointMemberService;

    @Autowired
    CarrotPointCommon carrotPointCommon;

    @Autowired
    CarrotPointConstant carrotPointConstant;

    /**
     * 최초 가입시 사용자 아이디로 중복 검사를 한다.
     *
     * @param carrotPointMember
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getMemberExistById", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CarrotPointMember getMemberExistById
            (@RequestBody CarrotPointMember carrotPointMember) throws Exception {
        logger.info("getMemberExistById");

        logger.info("memberId   : {}", carrotPointMember.getMemberId());
        logger.info("activateYn : {}", carrotPointMember.getActivateYn());

        return carrotPointMemberService.getMemberExistById(carrotPointMember);
    }

    /**
     * 사용자를 등록 한다.
     *
     * @param carrotPointMember
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/registerMember", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CarrotPointMember registerMember
            (@RequestBody CarrotPointMember carrotPointMember) throws Exception {
        logger.info("registerMember");

        CarrotPointMember result = new CarrotPointMember();

        try {
            carrotPointMemberService.registerMember(carrotPointMember);
            result.setResult("SUCCESS");
            logger.info("success to register member.");
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.info("fail to register member.");
        }

        return result;
    }

    /**
     * 사용자 정보를 가져 온다.
     *
     * @param carrotPointMember
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getMemberInformation", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CarrotPointMember getMemberInformation(@RequestBody CarrotPointMember carrotPointMember) throws Exception {
        logger.info("getMemberInformation");

        logger.info("memberId   : {}", carrotPointMember.getMemberId());
        logger.info("memberId   : {}", carrotPointCommon.getEncodedPassword(carrotPointMember.getMemberId()));
        logger.info("activateYn : {}", carrotPointMember.getActivateYn());

        return carrotPointMemberService.getMemberInformation(carrotPointMember);
    }

    /**
     * 이미지 파일을 전송 받아서 저장한 뒤 결과를 반환 한다.
     *
     * 원본 이미지 파일은 "/upload/profile/" 에 원본 포멧과 동일 하게 저장 하고,
     * 썸네일 이미지 파일을 만든 뒤 "/upload/thumb/" 에 PNG 포멧 으로 저장 한다.
     *
     *
     * @param memberId
     * @param imageFile
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadFile01", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CarrotPointMember uploadFile01(
            HttpServletRequest request,
            @RequestParam("memberId") String memberId,
            @RequestParam("nickName") String nickName,
            @RequestParam("imageFile") MultipartFile imageFile,
            @RequestParam("imageFileName") String imageFileName) throws Exception {
        logger.info("uploadFile01");

        CarrotPointMember result = new CarrotPointMember();

        try {
            logger.info("memberId               : {}", memberId);
            logger.info("checkMileageId encoded : {}", carrotPointCommon.getEncodedPassword(memberId));
            logger.info("nickName               : {}", nickName);
            logger.info("imageFile name         : {}", imageFileName);
            logger.info("imageFile size         : {}", imageFile.getSize()+" byte");

            if(!imageFile.isEmpty()) {
                // context path 를 가져 온다.
                String uploadPath = request.getSession().getServletContext().getRealPath("/");

                logger.info("path : {}", uploadPath + "upload/profile/");

                ImageFile parameter = new ImageFile();
                parameter.setCheckMileageId(memberId);
                parameter.setImageFile(imageFile);
                parameter.setUploadPath(uploadPath + "upload/profile/");

                // 서버에 원본 이미지 파일을 저장 한다.
                ImageFile resultImageFile = carrotPointCommon.uploadImageFile(parameter);

                String tempThumbnailImageFileName = resultImageFile.getTempFileName().substring(0, resultImageFile.getTempFileName().length()-4);

                File originalImageFile = new File(uploadPath + "upload/profile/" + resultImageFile.getTempFileName());
                // 생성 하려는 썸네일 이미지 파일의 확장자를 붙인다.
                File thumbnailImageFile = new File(uploadPath + "upload/thumbnail/" + tempThumbnailImageFileName + ".png");

                ImageFile thumbnailParameter = new ImageFile();
                thumbnailParameter.setOriginalImageFile(originalImageFile);
                thumbnailParameter.setThumbnailImageFile(thumbnailImageFile);
                thumbnailParameter.setThumbnailWidth(carrotPointConstant.THUMBNAIL_WIDTH);
                thumbnailParameter.setThumbnailHeight(carrotPointConstant.THUMBNAIL_HEIGHT);

                // 서버에 썸네일 이미지 파일을 만든 뒤 저장 한다.
                String thumbnailImageFileName = carrotPointCommon.createThumbnailImageFile(thumbnailParameter);

                logger.info("originalImageFileName on server  : {}", resultImageFile.getTempFileName());
                logger.info("thumbnailImageFileName on server : {}", thumbnailImageFileName);

                result.setResult("SUCCESS");
            } else {
                logger.info("Image file is empty.");
            }
        } catch (Exception e) {
            result.setResult("FAIL");
        }

        return result;
    }

    /**
     * 사용자의 정보를 업데이트 한다.
     *
     * @param carrotPointMember
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateMemberInformation", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CarrotPointMember updateMemberInformation(@RequestBody CarrotPointMember carrotPointMember) throws Exception {
        logger.info("updateMemberInformation");

        CarrotPointMember result = new CarrotPointMember();

        try {
            carrotPointMemberService.updateMemberInformation(carrotPointMember);
            result.setResult("SUCCESS");
            logger.info("success to update member information.");
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.info("fail to update member information.");
        }

        return result;
    }

    /**
     * 사용자의 GCM Registration Id / APNS Device Token 을 업데이트 한다.
     *
     * @param carrotPointMember
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateRegistrationId", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CarrotPointMember updateRegistrationId(@RequestBody CarrotPointMember carrotPointMember) throws Exception {
        logger.info("updateRegistrationId");

        CarrotPointMember result = new CarrotPointMember();

        try {
            carrotPointMemberService.updateRegistrationId(carrotPointMember);
            result.setResult("SUCCESS");
            logger.info("success to update registration id.");
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.info("fail to update registration id.");
        }

        return result;
    }

    /**
     * Push Notification 수신 여부를 업데이트 한다.
     *
     * @param carrotPointMember
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateReceiveNotificationYn", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CarrotPointMember updateReceiveNotificationYn(@RequestBody CarrotPointMember carrotPointMember) throws Exception {
        logger.info("updateReceiveNotificationYn");

        CarrotPointMember result = new CarrotPointMember();

        try {
            carrotPointMemberService.updateReceiveNotificationYn(carrotPointMember);
            result.setResult("SUCCESS");
            logger.info("success to update receive notification.");
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.info("fail to update receive notification.");
        }

        return result;
    }

    /**
     * 사용자의 위치 정보를 업데이트 한다.
     *
     * @param carrotPointMember
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateMemberLocation", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CarrotPointMember updateMemberLocation(@RequestBody CarrotPointMember carrotPointMember) throws Exception {
        logger.info("updateMemberLocation");

        CarrotPointMember result = new CarrotPointMember();

        try {
            carrotPointMemberService.updateMemberLocation(carrotPointMember);
            result.setResult("SUCCESS");
            logger.info("success to update member location.");
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.info("fail to update member location.");
        }

        return result;
    }

    /**
     * 사용자의 활성화 여부를 업데이트 한다.
     *
     * @param carrotPointMember
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateMemberActivateYn", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CarrotPointMember updateMemberActivateYn(@RequestBody CarrotPointMember carrotPointMember) throws Exception {
        logger.info("updateMemberActivateYn");

        CarrotPointMember result = new CarrotPointMember();

        try {
            carrotPointMemberService.updateMemberActivateYn(carrotPointMember);
            result.setResult("SUCCESS");
            logger.info("success to update member activateYn.");
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.info("fail to update member activateYn.");
        }

        return result;
    }

    /**
     * 전화번호로 기존 사용자가 있는지 확인 한다.
     *
     * @param carrotPointMember
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getMemberExistByPhoneNumber", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CarrotPointMember getMemberExistByPhoneNumber(@RequestBody CarrotPointMember carrotPointMember) throws Exception {
        logger.info("getMemberExistByPhoneNumber");

        return carrotPointMemberService.getMemberExistByPhoneNumber(carrotPointMember);
    }

    /**
     * 전화번호로 기존 사용자 정보를 가져 온다.
     *
     * @param carrotPointMember
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getMemberInformationByPhoneNumber", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CarrotPointMember getMemberInformationByPhoneNumber(@RequestBody CarrotPointMember carrotPointMember) throws Exception {
        logger.info("getMemberInformationByPhoneNumber");

        return carrotPointMemberService.getMemberInformationByPhoneNumber(carrotPointMember);
    }
}
